<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */
// Include twitteroauth
include 'Libs/twitter/twitteroauth.php';

class Twitter {

    //put your code here
    public $tweet;
    public static $instance;
    public $config = array(
        'consume_key' => 'D2aGP4LXcQERaMHZ9s7Flw',
        'consume_secret' => 'oguXr0RMGd99LdWeF7Y0CUckGbSWqp8VkVSGaNn4zs',
    );

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }

    public function __construct() {
        //allocate your stuff
    }

    public static function withData($token = NULL, $tokensecret = NULL) {
        $instance = self::getInstance();
        $instance->tweet = new TwitterOAuth($instance->config['consume_key'], $instance->config['consume_secret'], $token, $tokensecret);
        return $instance;
    }

    public static function getAuthorization($oauth_callback) {
        $instance = self::withData();
        $token = $instance->tweet->getRequestToken($oauth_callback);
        $newURL = $instance->tweet->getAuthorizeURL($token, TRUE);
        header("Location: $newURL");
        $_SESSION["token"] = $token["oauth_token"];
        $_SESSION["secret"] = $token["oauth_token_secret"];
    }

    public static function getCredentials() {
        $oauth_verifier = $_GET['oauth_verifier'];
        $instance = self::withData($_SESSION["token"], $_SESSION["secret"]);
        $credentials = $instance->tweet->getAccessToken($oauth_verifier);
        $checkTwitterId = Twitter::checkTwitterId($credentials["user_id"]);
        if($checkTwitterId == 1){
            $db = Database::getInstance();
            $id = $db->getID("twitters", "id");
            $userId = $_SESSION['userid'];
            $oauthtoken = $credentials["oauth_token"];
            $oauthtokensecret = $credentials["oauth_token_secret"];
            $twitterid = $credentials["user_id"];
            $screenname = $credentials["screen_name"];
            $query = "INSERT INTO twitters (id, userid, oauthtoken, oauthtokensecret,
                twitterid, screenname) VALUES ('$id', '$userId',  
                '$oauthtoken', '$oauthtokensecret', '$twitterid', '$screenname')";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return $twitterid;
            } else {
                return "false";
            }
        }else if($checkTwitterId != 0) {
            return $checkTwitterId;
        }
    }
//followers/ids.json?cursor=-1&screen_name=twitterapi
    public static function checkTwitterId($id) {
        $db = Database::getInstance();
        $query = "SELECT * FROM twitters WHERE twitterid = '$id'";
        $result = $db->query($query);
        if ($result->returnCode == 200)
            if ($result->dataTable->numOfRow == 0) {
                return 1;
            } else {
                $rows = $result->dataTable->rows[0];
                return $rows['twitterid'];
            }
        else
            return 0;
    }
    
    public static function getUserInfo($twitterId) {
        $db = Database::getInstance();
        $query = "SELECT * FROM twitters WHERE twitterid = '$twitterId'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow >= 0) {
                $rows = $result->dataTable->rows[0];
                $instance = self::withData($rows['oauthtoken'], $rows['oauthtokensecret']);
                $response = $instance->tweet->get('users/show', array('screen_name' => $rows["screenname"]));
                return $response;
            }else {
                return array();
            }
        } else {
            return array();
        }
    }
    
    public static function getTwitterFollowingTotal() {
       if (isset($_SESSION['userid'])) {
           $db = Database::getInstance();
           $userId = $_SESSION['userid'];
           $query = "SELECT * FROM twitters WHERE userid = '$userId'";
           $result = $db->query($query);
           if ($result->returnCode == 200) {
               if ($result->dataTable->numOfRow == 1) {
                   $rows = $result->dataTable->rows[0];
                   $instance = self::withData($rows['oauthtoken'], $rows['oauthtokensecret']);
                   $response = $instance->tweet->get('followers/ids', array('user_id' => $rows["twitterid"]));
                   if ($response != 200) {
                       return -1;
                   }
                   return sizeof($response["ids"]);
               }else {
                   return -1;
               }
           } else {
               return -1;
           }
       } else {
           return -1;
       }
    }
    
    public static function postTweet($messageId, $streamId, $message) {
        if (isset($_SESSION['userid'])) {
            $signalId = Signal::getId($messageId);
            if ($signalId != 0)
                $saveSignal = Signal::withId($signalId);
            else 
                $saveSignal = Signal::withData($messageId, $streamId);
            
            if ($saveSignal->retweetCount)
                $saveSignal->retweetCount++;
            else
                $saveSignal->retweetCount = 1;
            $signalController = new SignalController($saveSignal, new SignalView());
            $signalController->save();
            $db = Database::getInstance();
            $userId = $_SESSION['userid'];
            $query = "SELECT * FROM twitters WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow == 1) {
                    $rows = $result->dataTable->rows[0];
                    if (strlen($message) >= 140) {
                        $tempstr = substr($message, 0, 136);
                        $message = substr($message, 0, strripos($tempstr, " "));
                        $message .= '...';
                    }
                    $instance = self::withData($rows['oauthtoken'], $rows['oauthtokensecret']);
                    $response = $instance->tweet->post('statuses/update', array('status' => $message));
                    if ($response != 200 && $response != 302) {
                        if ($response == 403)
                            return "Cannot send a message twice.";
                        else
                            return "There was an error posting the message.";
                    }
                    return "Posted";
                }else {
                    return "Not found data";
                }
            } else {
                return "Cannot connect database";
            }
        } else {
            return "No user log in";
        }
    }

    public static function getTwitters() {
        if (isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $userId = $_SESSION['userid'];
            $query = "SELECT * FROM twitters WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['screenname'];
                        $id = $row['twitterid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                    return array(
                        "screenname" => $username,
                        "accountid" => $userid
                    );
                } else {
                    return array(
                        "screenname" => 'undefined',
                        "accountid" => 'undefined'
                    );
                }
            } else {
                return array(
                    "screenname" => 'undefined',
                    "accountid" => 'undefined'
                );
            }
        } else {
            return array(
                "screenname" => 'undefined',
                "accountid" => 'undefined'
            );
        }
    }

    public static function deleteTwitter($twitterid) {
        if (isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $query = "DELETE FROM twitters WHERE twitterid = '$twitterid'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            } else {
                return "false";
            }
        } else {
            return "false";
        }
    }

}

?>
